<?php

/**
 * 地域分析
 *
 * @author haifeng.wu
 */

require_once 'CommonController.php';
class Admin_AreaAnalyticsController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_DayAreaData();
        $this->view->title = "管理中心";
    }

    /**
     * 默认动作
     * 
     * @return void
     */
    public function indexAction()
    {
        $productPlatformModel = new Application_Model_ProductPlatform();
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();

        $vars = array();
        $wheres = array();
        $time = time();
        $vars['dateType'] = trim($this->_request->get('dateType')) != '' ? trim($this->_request->get('dateType')) : '1';
        $vars['osName'] = trim($this->_request->get('osName'));
        $vars['source'] = trim($this->_request->get('source'));
        $vars['sourceId'] = trim($this->_request->get('sourceId'));
        if ($vars['dateType'] == '1') {
            $vars['startDate'] = date("Y-m-d", $time - 3600 * 24 * 1);
            $vars['endDate'] = date("Y-m-d", $time - 3600 * 24 * 1);
        } else if ($vars['dateType'] == '2') {
            $vars['startDate'] = date("Y-m-d", $time - 3600 * 24 * 7);
            $vars['endDate'] = date("Y-m-d", $time - 3600 * 24 * 1);
        } else if ($vars['dateType'] == '3') {
            $vars['startDate'] = date("Y-m-d", $time - 3600 * 24 * 30);
            $vars['endDate'] = date("Y-m-d", $time - 3600 * 24 * 1);
        } else if ($vars['dateType'] == '4') {
            $vars['startDate'] = date("Y-m-d", $time - 3600 * 24 * 90);
            $vars['endDate'] = date("Y-m-d", $time - 3600 * 24 * 1);
        } else {
            $vars['startDate'] = trim($this->_request->get('startDate'));
            $vars['endDate'] = trim($this->_request->get('endDate'));
        }

        $platformRows = $productPlatformModel->fetchAll("`productCode` = '{$productCode}'");
        $memberRows = $this->_model->getMemberArray($productCode, $vars);
        
        $wheres[] = "`productCode` = '{$productCode}'";
        if (!empty($vars['startDate'])) {
            $wheres[] = "`date` >= '{$vars['startDate']}'";
        }
        if (!empty($vars['endDate'])) {
            $wheres[] = "`date` <= '{$vars['endDate']}'";
        }
        if (!empty($vars['osName'])) {
            $wheres[] = "`osName` = '" . addslashes($vars['osName']) . "'";
        }
        if (trim($vars['sourceId']) != '') {
            $wheres[] = "`sourceId` = '" . addslashes($vars['sourceId']) . "'";
        } else if (trim($vars['source']) != '') {
            $sourceModel = new Application_Model_Source();
            $memberModel = new Application_Model_Member();
            $wheres[] = "`sourceId`  IN (
                SELECT DISTINCT `s`.`sourceId` FROM
                `{$sourceModel->getTableName()}` AS `s` 
                INNER JOIN `{$memberModel->getTableName()}` AS `m` ON (`s`.`memberCode` = `m`.`code`)
                WHERE `s`.`productCode` = '{$productCode}' AND `m`.`name` = {$this->_model->getAdapter()->quote($vars['source'])}
            )";
        }

        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "SELECT `province`, SUM(`okOrderClientNum`) AS `okOrderClientNum`, SUM(`okOrderAmount`) AS `okOrderAmount`, SUM(`bootNum`) AS `bootNum`, SUM(`bootClientNum`) AS `bootClientNum`, SUM(`installNum`) AS `installNum` FROM `{$this->_model->getTableName()}` {$where} GROUP BY `province` ";

        $rows = $this->_model->getAdapter()->fetchAll($sql);

        $this->view->platformRows = $platformRows;
        $this->view->vars = $vars;
        $this->view->memberRows = $memberRows;
        $this->view->rows = $rows;
    }

    /**
     * 获取数据
     * 
     * @return void
     */
    public function getAreaDataAction()
    {
        $productPlatformModel = new Application_Model_ProductPlatform();
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();

        $vars = array();
        $wheres = array();
        $time = time();
        $vars['dateType'] = trim($this->_request->get('dateType')) != '' ? trim($this->_request->get('dateType')) : '1';
        $vars['osName'] = trim($this->_request->get('osName'));
        $vars['source'] = trim($this->_request->get('source'));
        $vars['sourceId'] = trim($this->_request->get('sourceId'));
        $vars['startDate'] = trim($this->_request->get('startDate'));
        $vars['endDate'] = trim($this->_request->get('endDate'));

        $wheres[] = "`productCode` = '{$productCode}'";
        if (!empty($vars['startDate'])) {
            $wheres[] = "`date` >= '{$vars['startDate']}'";
        }
        if (!empty($vars['endDate'])) {
            $wheres[] = "`date` <= '{$vars['endDate']}'";
        }
        if (!empty($vars['osName'])) {
            $wheres[] = "`osName` = '" . addslashes($vars['osName']) . "'";
        }
        if (trim($vars['sourceId']) != '') {
            $wheres[] = "`sourceId` = '" . addslashes($vars['sourceId']) . "'";
        } else if (trim($vars['source']) != '') {
            $sourceModel = new Application_Model_Source();
            $memberModel = new Application_Model_Member();
            $wheres[] = "`sourceId`  IN (
                SELECT DISTINCT `s`.`sourceId` FROM
                `{$sourceModel->getTableName()}` AS `s` 
                INNER JOIN `{$memberModel->getTableName()}` AS `m` ON (`s`.`memberCode` = `m`.`code`)
                WHERE `s`.`productCode` = '{$productCode}' AND `m`.`name` = {$this->_model->getAdapter()->quote($vars['source'])}
            )";
        }

        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "SELECT `province`, SUM(`okOrderClientNum`) AS `okOrderClientNum`, SUM(`okOrderAmount`) AS `okOrderAmount`, SUM(`bootNum`) AS `bootNum`, SUM(`bootClientNum`) AS `bootClientNum`, SUM(`installNum`) AS `installNum` FROM `{$this->_model->getTableName()}` {$where} GROUP BY `province` ORDER BY `bootClientNum` DESC";
        $rows = $this->_model->getAdapter()->fetchAll($sql);

        $areas = array();
        $areas[] = array('code' => 'CN.BJ', 'area' => '北京');
        $areas[] = array('code' => 'CN.HB', 'area' => '河北');
        $areas[] = array('code' => 'CN.TJ', 'area' => '天津');
        $areas[] = array('code' => 'CN.GD', 'area' => '广东');
        $areas[] = array('code' => 'CN.GX', 'area' => '广西');
        $areas[] = array('code' => 'CN.NM', 'area' => '内蒙古');
        $areas[] = array('code' => 'CN.AH', 'area' => '安徽');
        $areas[] = array('code' => 'CN.CQ', 'area' => '重庆');
        $areas[] = array('code' => 'CN.FJ', 'area' => '福建');
        $areas[] = array('code' => 'CN.GS', 'area' => '甘肃');
        $areas[] = array('code' => 'CN.GZ', 'area' => '贵州');
        $areas[] = array('code' => 'CN.HA', 'area' => '海南');
        $areas[] = array('code' => 'CN.HE', 'area' => '河南');
        $areas[] = array('code' => 'CN.HU', 'area' => '湖北');
        $areas[] = array('code' => 'CN.HL', 'area' => '黑龙江');
        $areas[] = array('code' => 'CN.HN', 'area' => '湖南');
        $areas[] = array('code' => 'CN.JS', 'area' => '江苏');
        $areas[] = array('code' => 'CN.JX', 'area' => '江西');
        $areas[] = array('code' => 'CN.JL', 'area' => '吉林');
        $areas[] = array('code' => 'CN.LN', 'area' => '辽宁');
        $areas[] = array('code' => 'CN.NX', 'area' => '宁夏');
        $areas[] = array('code' => 'CN.QH', 'area' => '青海');
        $areas[] = array('code' => 'CN.SA', 'area' => '陕西');
        $areas[] = array('code' => 'CN.SD', 'area' => '山东');
        $areas[] = array('code' => 'CN.SH', 'area' => '上海');
        $areas[] = array('code' => 'CN.SX', 'area' => '山西');
        $areas[] = array('code' => 'CN.SC', 'area' => '四川');
        $areas[] = array('code' => 'CN.XJ', 'area' => '新疆');
        $areas[] = array('code' => 'CN.XZ', 'area' => '西藏');
        $areas[] = array('code' => 'CN.YN', 'area' => '云南');
        $areas[] = array('code' => 'CN.ZJ', 'area' => '浙江');
        $areas[] = array('code' => 'CN.HK', 'area' => '香港');
        $areas[] = array('code' => 'CN.MA', 'area' => '澳门');
        $areas[] = array('code' => 'CN.TA', 'area' => '台湾');
        
        $areaData = array();
        $count['okOrderClientNum'] = 0;
        $okOrderClientNumPreviousNum = 0;
        foreach($rows as $key=>$row) {
            $row['areaCode'] = '';
            $row['area'] = '';

            if ($key > 0) {
                if ($row['okOrderClientNum'] < $okOrderClientNumPreviousNum) {
                    $row['order'] = $rows[$key - 1]['order'] + 1;
                } else {
                    $row['order'] = $rows[$key - 1]['order'];
                }
            } else {
                $row['order'] = 1;
            }
            $okOrderClientNumPreviousNum = $row['okOrderClientNum'];

            foreach($areas as $area) {
                if ($area['area'] == $row['province']) {
                    $row['areaCode'] = $area['code'];
                    $row['area'] = $area['area'];
                    $count['okOrderClientNum'] += $row['okOrderClientNum'];
                    break; 
                }
            }
            $rows[$key] = $row;
        }
        $this->view->rows = $rows;
        $this->view->count = $count;
    }

    /**
     * 获取sourceId
     * @return json string
     */
    public function sourceidsAction() 
    {
        $source = trim($this->_request->getPost('source'));
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        
        $rows = $this->_model->getSourceIdArrayByMember($productCode, $source);
        $res = array();
        foreach($rows as $row) {
            $res[]=$row['sourceId'];
        }
        $json = json_encode($res);
        exit($json);
        
    }

}